/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jakroatis;

import java.io.Console;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Jose Carlos Palma
 */
public class Consola extends ThreadPlus {

    private Console in;
    private HashMap<String, ThreadPlus> maps = new HashMap<String, ThreadPlus>(10);

    public Consola() {
        super("Consola");
        this.in = System.console();
        
    }

    public void addService(ThreadPlus service) {
        maps.put(service.getName(), service);
    }

    @Override
    public void core() {

        in.printf("%s", "$ ");
        String cmd = in.readLine();

        if (cmd.matches("^(q|quit|exit|shutdown)$")) {
            for( ThreadPlus s: maps.values() ){
                s.serviceStop();
            }
            serviceStop();
        } else if (cmd.startsWith("start")) {
            String[] args = cmd.split(" ", 2);
            String arg = "";
            if (args.length == 2) {
                arg = args[1];
            }
            if (!cmd.matches("^start (all|[a-zA-Z0-9]+)$")) {
                in.printf("%s: Illegal argument \"%s\"\n", "start", arg);
                in.printf("%s\n", "usage: start all|<servieName>");
            } else if (arg.equals("all")) {
                for (ThreadPlus s : maps.values()) {
                    s.serviceStart();
                }
            } else {
                ThreadPlus s = maps.get(arg);
                if (s == null) {
                    in.printf("%s: service \"%s\" not found\n", "start", arg);
                    in.printf("%s\n", "usage: start all|<servieName>");
                } else {
                    s.serviceStart();
                }
            }
        } else if (cmd.startsWith("stop")) {
        } else if (cmd.matches("^stop (all|[a-zA-Z0-9]+)$")) {
        } else if (cmd.matches("^status (all|[a-zA-Z0-9]+)$")) {
        } else if (cmd.matches("^restart$")) {
            serviceRestart();
        } else {
            System.out.println("\"" + cmd + "\" command not found");
        }

    }

    @Override
    public void serviceStatus() {
        in.printf("%s [%s]\n", getName() ,"On");
    }

    @Override
    public void serviceStart() {
        in.printf("%s is starting...\n", getName());
        start();
    }

    @Override
    public void serviceRestart() {
        
    }

    @Override
    public void serviceStop() {
        in.printf("Service %s is stoping...\n", getName());
        shutdown();
        while( !isShutdown() ){
            pause(200);
        }
        in.printf("%s [%s]\n", getName(), "Off");
        
    }
}
